package com.yunhe.abnormal.service.base.impl;

import com.yunhe.abnormal.client.AuthorityClient;
import com.yunhe.abnormal.domain.base.AlarmType;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.abnormal.mapper.base.AlarmTypeMapper;
import com.yunhe.common.model.PageParam;
import com.yunhe.common.model.authority.UserDTO;
import com.yunhe.common.model.base.AlarmTypeDTO;
import com.yunhe.abnormal.repository.base.AlarmTypeRepository;
import com.yunhe.abnormal.repository.base.AlarmTypeSession;
import com.yunhe.abnormal.service.base.AlarmTypeService;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.HeaderUtil;
import com.yunhe.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 异常类型Service
 * @author liuronglei
 */
@Service
public class AlarmTypeServiceImpl implements AlarmTypeService {

    @Autowired
    private AlarmTypeRepository alarmTypeRepository;
    @Autowired
    private AlarmTypeSession alarmTypeSession;
    @Autowired
    private AlarmTypeMapper mapper;
    @Autowired
    private HeaderUtil headerUtil;
    @Autowired
    private AuthorityClient authorityClient;

    /**
     * 异常类型对象处理和判断
     * @param alarmType 异常类型对象
     */
    private void processBeforeSave(AlarmType alarmType)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        // 判断异常类型标题是否为空
        if (StringUtil.isEmpty(alarmType.getTitle())) {
            throw new ArgumentErrorException("异常类型标题不能为空");
        }
        // 判断标题是否已存在
        AlarmTypeDTO typeByTitle = this.findByTitle(alarmType.getTitle());
        if (typeByTitle != null) {
            if (alarmType.getId() == null || typeByTitle.getId().longValue() != alarmType.getId().longValue()) {
                throw new UniqueConstraintsException("该异常类型已存在");
            }
        }
        // 更新维护人和维护时间
        Long userId = headerUtil.getHeaderUserId();
        String userTitle = null;
        String timeZone = null;
        if (userId != null) {
            UserDTO user = authorityClient.getUserById(userId).getBody().getResults();
            if (user != null) {
                userTitle = user.getTitle();
                timeZone = user.getTimeZone();
            }
        }
        Long rtime = System.currentTimeMillis();
        String dtime = DateTimeUtils.getDateString(rtime, timeZone);
        alarmType.setRtime(rtime);
        alarmType.setDtime(dtime);
        alarmType.setUserId(userId);
        alarmType.setUserTitle(userTitle);
    }

    @Override
    public AlarmTypeDTO create(AlarmTypeDTO alarmType) throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        AlarmType myAlarmType = mapper.from(alarmType);
        processBeforeSave(myAlarmType);
        return mapper.to(alarmTypeRepository.save(myAlarmType));
    }

    @Override
    public AlarmTypeDTO findById(Long id) {
        return mapper.to(alarmTypeRepository.findById(id).orElse(null));
    }

    @Override
    public AlarmTypeDTO findByTitle(String title) {
        return mapper.to(alarmTypeRepository.findByTitle(title));
    }

    @Override
    public void deleteById(Long id) {
        alarmTypeRepository.deleteById(id);
    }

    @Override
    public AlarmTypeDTO update(Long id, String title, String desc) throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        AlarmType alarmType = alarmTypeRepository.findById(id).orElse(null);
        if (alarmType == null) {
            throw new ObjectNotFoundException("找不到ID为" + id + "的异常类型");
        }
        alarmType.setTitle(title);
        alarmType.setDesc(desc);
        processBeforeSave(alarmType);
        return mapper.to(alarmTypeRepository.save(alarmType));
    }

    @Override
    public AlarmTypeDTO update(AlarmTypeDTO alarmType) throws ArgumentErrorException, ObjectNotFoundException, UniqueConstraintsException {
        AlarmType byId = alarmTypeRepository.findById(alarmType.getId()).orElse(null);
        if (byId == null) {
            throw new ObjectNotFoundException("找不到ID为" + alarmType.getId() + "的异常类型");
        }
        byId.setTitle(alarmType.getTitle());
        byId.setDesc(alarmType.getDesc());
        processBeforeSave(byId);
        return mapper.to(alarmTypeRepository.save(byId));
    }

    @Override
    public void batchDelete(List<Long> ids) {
        if (ids !=null && !ids.isEmpty()) {
            for (Long id : ids) {
                alarmTypeRepository.deleteById(id);
            }
        }
    }

    @Override
    public Iterable<AlarmTypeDTO> search(String queryStr, List<String> dtime, PageParam pageParam) {
        List<Long> rtime = new ArrayList<>();
        if (dtime != null && !dtime.isEmpty()) {
            for (String dtimeStr : dtime) {
                rtime.add(DateTimeUtils.getTimestamp(dtimeStr, null));
            }
        }
        Page<AlarmType> page = alarmTypeSession.findByKeywordAndDtime(queryStr, rtime, pageParam);
        List<AlarmType> content = page.getContent();
        List<AlarmTypeDTO> to = mapper.to(content);
        return new PageImpl<>(to, page.getPageable(), page.getTotalElements());
    }

    @Override
    public List<Long> getBoundRule(List<Long> ids) {
        return alarmTypeSession.getBoundRule(ids);
    }
}
